<template>
    <view class="container">
        <custom-nav-bar title="营地详情" :showBack="true" />
        <view class="content">
            <!-- 营地基本信息 -->
            <swiper class="banner-swiper" circular indicator-dots>
                <swiper-item>
                    <image :src="campInfo.imageUrl" mode="aspectFill" class="banner-image" />
                </swiper-item>
            </swiper>

            <view class="camp-info">
                <view class="camp-header">
                    <text class="camp-name">{{ campInfo.name }}</text>
                    <view class="favorite-btn" @tap="toggleFavorite">
                        <image :src="isFavorite ? '/static/icons/star-filled.png' : '/static/icons/star.png'"
                            mode="aspectFit" class="favorite-icon" />
                    </view>
                </view>
                <text class="camp-description">{{ campInfo.description }}</text>
                <view class="camp-meta">
                    <text class="camp-score">{{ campInfo.score }}分</text>
                </view>
                <text class="camp-address">{{ campInfo.address }}</text>
                <view class="price-info">
                    <text class="price">¥{{ campInfo.price }}</text>
                    <text class="price-label">/天</text>
                </view>
            </view>

            <!-- 预订须知 -->
            <view class="booking-info">
                <view class="info-title">预订须知</view>
                <view class="info-list">
                    <view class="info-item">
                        <text class="item-label">营业时间：</text>
                        <text>{{ campInfo.businessHours }}</text>
                    </view>
                    <view class="info-item">
                        <text class="item-label">人数限制：</text>
                        <text>最多{{ campInfo.maxGuests }}人/帐</text>
                    </view>
                    <view class="info-item">
                        <text class="item-label">入住押金：</text>
                        <text>¥{{ campInfo.deposit }}/帐</text>
                    </view>
                </view>
            </view>

            <!-- 底部预订按钮 -->
            <view class="booking-bar">
                <button class="booking-btn" @tap="onBooking">立即预订</button>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, toRaw, getCurrentInstance } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { favoriteApi, orderApi } from '@/api/index'
import CustomNavBar from '@/components/custom-nav-bar/custom-nav-bar.vue'

// 定义响应式数据
const campInfo = ref({
    id: '',
    name: '',
    imageUrl: '',
    score: '',
    description: '',
    price: '',
    address: '',
    cityId: '',
    categoryId: '',
    businessHours: '9:00-22:00',
    maxGuests: '12',
    deposit: '1000.00',
    status: '1'
})
const isFavorite = ref(false) // 是否已收藏

// 页面加载时处理数据
onLoad((options) => {
    console.log('详情页 onLoad:', options)
    // 从URL参数中获取营地数据
    if (options) {
        campInfo.value = {
            ...campInfo.value,
            id: options.id,
            name: decodeURIComponent(options.name),
            imageUrl: decodeURIComponent(options.imageUrl),
            score: options.score,
            distance: options.distance,
            price: options.price
        }
        console.log('更新后的campInfo:', campInfo.value)
        checkFavoriteStatus()
    }
})

// 检查收藏状态
const checkFavoriteStatus = async () => {
    try {
        const userInfo = uni.getStorageSync('userInfo')
        if (!userInfo || !userInfo.id) {
            return
        }

        const res = await favoriteApi.checkFavorite(userInfo.id, campInfo.value.id, 'camp')
        isFavorite.value = res.data
    } catch (error) {
        console.error('检查收藏状态失败:', error)
    }
}

// 切换收藏状态
const toggleFavorite = async () => {
    try {
        const userInfo = uni.getStorageSync('userInfo')
        if (!userInfo || !userInfo.id) {
            uni.showToast({
                title: '请先登录',
                icon: 'none'
            })
            return
        }

        if (isFavorite.value) {
            // 取消收藏
            await favoriteApi.deleteFavorite(userInfo.id, campInfo.value.id, 'camp')
            uni.showToast({
                title: '已取消收藏',
                icon: 'success'
            })
        } else {
            // 添加收藏
            await favoriteApi.addFavorite(userInfo.id, campInfo.value.id, 'camp')
            uni.showToast({
                title: '已加入收藏',
                icon: 'success'
            })
        }
        // 更新收藏状态
        isFavorite.value = !isFavorite.value
    } catch (error) {
        console.error('操作收藏失败:', error)
        uni.showToast({
            title: '操作失败',
            icon: 'none'
        })
    }
}

// 预订按钮点击处理
const onBooking = async () => {
    const userInfo = uni.getStorageSync('userInfo')
    if (!userInfo || !userInfo.id) {
        uni.showToast({
            title: '请先登录',
            icon: 'none'
        })
        return
    }

    try {
        // 创建订单数据
        const orderData = {
            userId: userInfo.id,
            campId: campInfo.value.id,
            campName: campInfo.value.name,
            price: campInfo.value.price,
            image: campInfo.value.imageUrl,
            status: 'pending', // 初始状态为待支付
            bookingDate: new Date().toISOString(), // 预订日期
        }

        // 调用创建订单接口
        const res = await orderApi.createOrder(orderData)
        // 判断是否成功：如果 res.code 是 200 或者 res.msg 包含"成功"字样都认为是成功
        if (res.code === 200 || (res.msg && res.msg.includes('成功'))) {
            // 先显示提示
            await new Promise((resolve) => {
                uni.showToast({
                    title: '预订成功',
                    icon: 'success',
                    success: () => {
                        resolve()
                    }
                })
            })

            // 使用 redirectTo 而不是 navigateTo，这样可以关闭当前页面
            uni.redirectTo({
                url: '/pages/booking/index',
                fail: (err) => {
                    console.error('跳转失败:', err)
                    // 如果 redirectTo 失败，尝试使用 switchTab（如果订单页是 tabBar 页面）
                    uni.switchTab({
                        url: '/pages/booking/index'
                    })
                }
            })
        } else {
            throw new Error(res.msg || '预订失败')
        }
    } catch (error) {
        // 如果错误信息包含"成功"，说明其实是成功的
        if (error.message && error.message.includes('成功')) {
            // 先显示提示
            await new Promise((resolve) => {
                uni.showToast({
                    title: '预订成功',
                    icon: 'success',
                    success: () => {
                        resolve()
                    }
                })
            })

            // 使用 redirectTo 而不是 navigateTo
            uni.redirectTo({
                url: '/pages/booking/index',
                fail: (err) => {
                    console.error('跳转失败:', err)
                    // 如果 redirectTo 失败，尝试使用 switchTab
                    uni.switchTab({
                        url: '/pages/booking/index'
                    })
                }
            })
        } else {
            console.error('预订失败:', error)
            uni.showToast({
                title: error.message || '预订失败',
                icon: 'none'
            })
        }
    }
}
</script>

<style>
.container {
    padding-bottom: 100rpx;
    padding-top: var(--status-bar-height);
}

.content {
    padding-top: 44px;
    /* 导航栏高度 */
}

.banner-swiper {
    width: 100%;
    height: 400rpx;
}

.banner-image {
    width: 100%;
    height: 100%;
}

.camp-info {
    padding: 30rpx;
    background: #fff;
}

.camp-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
}

.camp-name {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
}

.favorite-btn {
    padding: 10rpx;
}

.favorite-icon {
    width: 48rpx;
    height: 48rpx;
}

.camp-description {
    margin-top: 10rpx;
    font-size: 28rpx;
    color: #666;
}

.camp-meta {
    margin-top: 20rpx;
    display: flex;
    align-items: center;
}

.camp-score {
    color: #ff9800;
    margin-right: 20rpx;
}

.camp-address {
    margin-top: 10rpx;
    font-size: 28rpx;
    color: #666;
}

.price-info {
    margin-top: 20rpx;
    display: flex;
    align-items: baseline;
}

.price {
    font-size: 40rpx;
    font-weight: bold;
    color: #f56c6c;
}

.price-label {
    font-size: 24rpx;
    color: #999;
    margin-left: 4rpx;
}

.booking-info {
    margin-top: 20rpx;
    background: #fff;
    padding: 30rpx;
}

.info-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
}

.info-list {
    margin-top: 10rpx;
}

.info-item {
    display: flex;
    margin-bottom: 16rpx;
    font-size: 28rpx;
}

.item-label {
    color: #666;
    margin-right: 20rpx;
}

.booking-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100rpx;
    background: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 30rpx;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.booking-btn {
    width: 200rpx;
    height: 72rpx;
    line-height: 72rpx;
    background: #409eff;
    color: #ffffff;
    font-size: 28rpx;
    border-radius: 36rpx;
}

.booking-btn::after {
    border: none;
}
</style>